package com.viphuli.app.tool.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;

import com.loopj.android.http.RequestParams;
import com.mobeta.android.dslv.DragSortListView;
import com.offroader.utils.DateUtils;
import com.offroader.utils.JsonUtils;
import com.offroader.utils.StringUtils;
import com.offroader.utils.ViewUtils;
import com.viphuli.app.tool.R;
import com.viphuli.app.tool.bean.PageBaseBean;
import com.viphuli.app.tool.bean.page.ArrangeActionPage;
import com.viphuli.app.tool.bean.part.AccountUser;
import com.viphuli.app.tool.bean.part.ArrangeType;
import com.viphuli.app.tool.bean.part.ArrangeView;
import com.viphuli.app.tool.common.AccessTokenKeeper;
import com.viphuli.app.tool.common.Constants;
import com.viphuli.app.tool.handler.ArrangeWeekViewResponseHandler.DayUserArrangeHolder;
import com.viphuli.app.tool.http.ApiRequest;
import com.viphuli.app.tool.utils.OtherUtils;

public class ArrangeViewWeekFragment extends BaseProgressFragment implements OnItemSelectedListener {

	@Bind(R.id.id_arrange_detail_week_time)
	protected Spinner spinner;

	@Bind(R.id.id_view_week_header)
	protected ViewGroup viewWeekHeaderLayout;

	@Bind(R.id.id_view_week_layout)
	protected ViewGroup viewWeekLayout;

	@Bind(R.id.id_arrange_layout_exchange)
	protected ViewGroup exchangeLayout;

	@Bind(R.id.id_arrange_layout)
	protected ViewGroup arrangeLayout;

	@Bind(R.id.id_arrange_type_layout)
	protected ViewGroup arrangeTypeLayout;

	@Bind(R.id.id_arrange_btn_replace)
	protected View arrangeBtnReplace;

	@Bind(R.id.id_arrange_btn_exchange)
	protected View arrangeBtnExchange;

	@Bind(R.id.id_arrange_btn_exchange_action)
	protected View arrangeBtnExchangeAction;

	@Bind(R.id.id_view_week_remark)
	protected TextView weekRemark;
	
	@Bind(R.id.id_listview)
	protected DragSortListView listview;

	//排班类型列表
	private List<ArrangeType> arrangeTypeList;
	
	private List<ArrangeView> arrangeViewList = new ArrayList<ArrangeView>();

	//排班类型：1 排班，2 换班&替班
	private int actionType;

	//当前操作类型：1：排班，2：调班，3：替班
	private int type = -1;

	//当前点击的天
	private ViewGroup clickView;

	//当前显示第几个
	private int curWhich;

	//操作确定结果集
	private List<Integer> arrangeIds = new ArrayList<Integer>();

	//某人某一天的排班信息
	private List<DayUserArrangeHolder> dayUserArrangeHolderList = new ArrayList<DayUserArrangeHolder>();

	//默认选择的人
	private String defSelectUid;
	//默认选择的班次
	private long defSelectTime;

	private long time;

	private Map<Integer, Date> data;

	@Override
	protected int obtainContentRes() {
		return R.layout.frag_week_view;
	}

	@SuppressLint("NewApi")
	@Override
	protected void initParams() {
		Bundle args = getArguments();

		//操作类型
		actionType = args.getInt("action_type", 0);

		//默认选择某个班次
		defSelectUid = args.getString("def_select_uid", "");
		defSelectTime = args.getLong("def_select_time", 0);
	}

	@Override
	protected void initView() {
		
		if (ArrangeViewFragment.ACTION_ARRANGE == actionType) {//排班
			weekRemark.setEnabled(true);
			exchangeLayout.setVisibility(View.GONE);
			
		} else if (ArrangeViewFragment.ACTION_EXCHANGE == actionType) {//替班&换班
			weekRemark.setEnabled(false);
			weekRemark.setHint("无");
			arrangeLayout.setVisibility(View.GONE);

			exchangeLayout.setVisibility(View.GONE);
			arrangeTypeLayout.setVisibility(View.GONE);
			arrangeBtnReplace.setVisibility(View.GONE);
			arrangeBtnExchange.setVisibility(View.GONE);
			arrangeBtnExchangeAction.setVisibility(View.GONE);

		}

		time = System.currentTimeMillis();

	}

	@Override
	protected void initData() {

		//顶部
		initTopWeekTime();
		
	}

	public void weekViewRequest(int year, int which) {
		curWhich = which;

		AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());

		if (tokenKeeper.isLogin()) {

			//当前周第一天
			List<Date> dayList = DateUtils.dateToWeek(year, which);

			long firstDayWeek = OtherUtils.maxLength(dayList.iterator().next().getTime());
			
			time = firstDayWeek;

			RequestParams params = new RequestParams();
			params.put("which", which);
			params.put("type", Constants.ARRANGE_ACTION_TYPE_ARRANGE);
			params.put("uid", tokenKeeper.getOpenId());
			params.put("circle_id", tokenKeeper.getUser().circleId());
			params.put("time", firstDayWeek);

			//取周视图数据
			ApiRequest.arrangeWeekView.request(this, params);

		}
	}
	
	/**
	 * 初始化项部周列表
	 * @param time
	 */
	private void initTopWeekTime() {

		int nowYear = DateUtils.getYear(new Date(time));//哪年
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
		List<String> weekLineDataList = new ArrayList<String>();
		Date now = new Date(time);

		data = new HashMap<Integer, Date>();

		//前后三年的数据
		List<Integer> years = Arrays.asList(nowYear - 1, nowYear, nowYear + 1);

		int index = -1;

		for (int year : years) {

			int weekCountYear = DateUtils.getWeekCountByYear(year);

			for (int i = 0; i < weekCountYear; i++) {//遍历周

				index++;

				int week = i + 1;

				List<Date> weekDates = DateUtils.dateToWeek(year, week);

				int y = DateUtils.getYear(weekDates.iterator().next());
				int m = DateUtils.getMonthInYear(weekDates.iterator().next());
				int w = DateUtils.getWeekInMonth(weekDates.iterator().next());

				//当前信息
				Date d = weekDates.iterator().next();
				data.put(index, weekDates.iterator().next());

				if (y == DateUtils.getYear(now) && m == DateUtils.getMonthInYear(now) && w == DateUtils.getWeekInMonth(now)) {
					curWhich = index;
				}

				if (i == 0) {//当第一周时， 取本周最后一天的年月

					Date lastDateOfWeek = weekDates.get(weekDates.size() - 1);
					String yearMonth = sdf.format(lastDateOfWeek);

					String data = yearMonth + " 第" + week + "周";
					weekLineDataList.add(data);

				} else if (i == 0) {//当最后周时，取本周第一天的年月

					Date firstDateOfWeek = weekDates.get(0);
					String yearMonth = sdf.format(firstDateOfWeek);

					String data = yearMonth + " 第" + week + "周";
					weekLineDataList.add(data);

				} else {//其它情况，当前周任意天即可

					Date firstDateOfWeek = weekDates.get(0);
					String yearMonth = sdf.format(firstDateOfWeek);

					String data = yearMonth + " 第" + week + "周";
					weekLineDataList.add(data);

				}

			}

		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_arrange_view, weekLineDataList);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);

		//		int selectWeek = DateUtils.getWeekInYear(new Date(System.currentTimeMillis()));
		spinner.setSelection(curWhich);

		spinner.setOnItemSelectedListener(this);

	}

	/**
	 * 点击替班
	 */
	@OnClick(R.id.id_arrange_btn_replace)
	public void clickArrangeReplace() {
		type = Constants.ARRANGE_ACTION_TYPE_REPLACE;//替班

		if (dayUserArrangeHolderList.size() == 1) {

			DayUserArrangeHolder dayUserArrangeHolder = dayUserArrangeHolderList.iterator().next();
			List<ArrangeType> arrangeTypeList = dayUserArrangeHolder.getArrangeTypeList();

			if (arrangeTypeList.size() > 1 && dayUserArrangeHolder.getCheck() != -1 || arrangeTypeList.size() == 1) {
				//								exchangeLayout.setVisibility(View.GONE);

				//跳转新的替班界面
				Bundle args = new Bundle();
				args.putString("day_user_arrange_holder", JsonUtils.toJson(dayUserArrangeHolder));

				ArrangeActionReplaceFragment.go(getActivity(), args);

			} else {
				ViewUtils.toast("请选择排班");
			}

		}

	}

	/**
	 * 点击换班
	 */
	@OnClick(R.id.id_arrange_btn_exchange)
	public void clickArrangeExchange() {
		type = Constants.ARRANGE_ACTION_TYPE_EXCHANGE;//换班

		if (dayUserArrangeHolderList.size() == 1) {

			DayUserArrangeHolder dayUserArrangeHolder = dayUserArrangeHolderList.iterator().next();
			List<ArrangeType> arrangeTypeList = dayUserArrangeHolder.getArrangeTypeList();

			if (arrangeTypeList.size() > 1 && dayUserArrangeHolder.getCheck() != -1 || arrangeTypeList.size() == 1) {
				exchangeLayout.setVisibility(View.GONE);
			} else {
				ViewUtils.toast("请选择排班");
			}

		}
	}

	/**
	 * 点击完成(换班，替班)
	 */
	@OnClick(R.id.id_arrange_btn_exchange_action)
	public void arrangeExchangeAction() {

		if (dayUserArrangeHolderList.size() == 2) {

			List<ArrangeType> arrangeTypeList = dayUserArrangeHolderList.get(1).getArrangeTypeList();

			if (arrangeTypeList.size() > 1 && dayUserArrangeHolderList.get(1).getCheck() != -1 || arrangeTypeList.size() == 1) {

				DayUserArrangeHolder dayUserArrangeHolder = dayUserArrangeHolderList.get(0);
				arrangeExchange(dayUserArrangeHolder);

			} else {
				ViewUtils.toast("请选择排班");
			}

		}

	}

	/**
	 * 确定(排班)
	 */
	@OnClick(R.id.id_arrange_btn)
	public void arrangeAction() {

		AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());

		if (tokenKeeper.isLogin()) {

			StringBuilder arrangeIdBuider = new StringBuilder();
			for (int i = 0; i < arrangeIds.size(); i++) {

				if (i != 0)
					arrangeIdBuider.append(",");

				arrangeIdBuider.append(arrangeIds.get(i));

			}

			RequestParams params = new RequestParams();
			params.put("uid", tokenKeeper.getOpenId());
			params.put("arrange_info_ids", arrangeIdBuider.toString());
			params.put("type", type);//1：排班，2：调班，3：替班
			params.put("circle_id", tokenKeeper.getUser().circleId());
			params.put("remark", StringUtils.EMPTY);

			//备注用
			int year = DateUtils.getYear(new Date(OtherUtils.getNeedTime(time)));
			params.put("week_remark", weekRemark.getText().toString());
			params.put("year", year);
			params.put("week", curWhich);

			ApiRequest.arrangeActionConfirm.request(this, params);
		}

	}

	@Override
	public void onRequestResonse(PageBaseBean page) {
		super.onRequestResonse(page);

		//操作结果记录
		ArrangeActionPage actionPage = (ArrangeActionPage) page;
		arrangeIds.add(actionPage.getArrangeInfo().getId());

		if (arrangeIds.size() == 1) {//触发换班&替班

			DayUserArrangeHolder dayUserArrangeHolder = dayUserArrangeHolderList.get(1);
			arrangeExchange(dayUserArrangeHolder);

		} else if (arrangeIds.size() == 2) {//触发完成

			arrangeExchangeConfirm();

		}
	}

	/**
	 * 确定（换班&替班）
	 */
	public void arrangeExchangeConfirm() {
		if (arrangeIds.isEmpty() || arrangeIds.size() != 2) {
			return;
		}

		if (dayUserArrangeHolderList.size() == 2) {

			DayUserArrangeHolder dayUserArrangeHolder = dayUserArrangeHolderList.get(1);
			List<ArrangeType> arrangeTypeList = dayUserArrangeHolder.getArrangeTypeList();

			if (arrangeTypeList.size() > 1 && dayUserArrangeHolder.getCheck() != -1 || arrangeTypeList.size() == 1) {

				AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());

				if (tokenKeeper.isLogin()) {

					StringBuilder arrangeIdBuider = new StringBuilder();

					for (int i = 0; i < arrangeIds.size(); i++) {

						if (i != 0)
							arrangeIdBuider.append(",");

						arrangeIdBuider.append(arrangeIds.get(i));

					}

					RequestParams params = new RequestParams();
					params.put("uid", tokenKeeper.getOpenId());
					params.put("arrange_info_ids", arrangeIdBuider.toString());
					params.put("type", type);//1：排班，2：调班，3：替班
					params.put("circle_id", tokenKeeper.getUser().circleId());
					params.put("remark", StringUtils.EMPTY);

					ApiRequest.arrangeActionConfirm.request(this, params);
				}

			} else {
				ViewUtils.toast("请选择排班");
			}

		}
	}

	public void arrangeExchange(DayUserArrangeHolder dayUserArrangeHolder) {

		List<ArrangeType> arrangeTypeList = dayUserArrangeHolder.getArrangeTypeList();

		if (arrangeTypeList.size() > 1 && dayUserArrangeHolder.getCheck() != -1 || arrangeTypeList.size() == 1) {

			AccountUser toUser = dayUserArrangeHolder.getUser();
			Date date = dayUserArrangeHolder.getDate();

			AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(getActivity());

			if (tokenKeeper.isLogin()) {

				RequestParams params = new RequestParams();

				if (type == Constants.ARRANGE_ACTION_TYPE_REPLACE) {//替班

					if (arrangeIds.size() == 0) {

						params.put("uid", tokenKeeper.getOpenId());
						params.put("to_uid", toUser.getUid());
						params.put("time", OtherUtils.maxLength(date.getTime()));
						params.put("circle_id", tokenKeeper.getUser().circleId());
						params.put("type", type);//1排班,2换班,3替班

						if (arrangeTypeList != null || !arrangeTypeList.isEmpty()) {
							for (ArrangeType type : this.arrangeTypeList) {
								if (type.getType() == 2) {//免费的类型
									params.put("arrange_type_id", type.getId());
									break;
								}
							}
						}

					} else if (arrangeIds.size() == 1) {

						params.put("uid", tokenKeeper.getOpenId());
						params.put("to_uid", toUser.getUid());
						params.put("time", OtherUtils.maxLength(date.getTime()));
						params.put("circle_id", tokenKeeper.getUser().circleId());
						params.put("type", type);//1排班,2换班,3替班

						DayUserArrangeHolder targetDayUserArrangeHolder = dayUserArrangeHolderList.get(0);
						List<ArrangeType> targetArrangeTypeList = targetDayUserArrangeHolder.getArrangeTypeList();

						ArrangeType targetArrangeType = null;
						if (targetArrangeTypeList.size() > 1) {
							targetArrangeType = targetArrangeTypeList.get(targetDayUserArrangeHolder.getCheck());
						} else {
							targetArrangeType = targetArrangeTypeList.iterator().next();
						}

						params.put("arrange_type_id", targetArrangeType.getId());

					}

				} else if (type == Constants.ARRANGE_ACTION_TYPE_EXCHANGE) {//换班

					if (arrangeIds.size() == 0) {

						DayUserArrangeHolder targetDayUserArrangeHolder = dayUserArrangeHolderList.get(1);
						List<ArrangeType> targetArrangeTypeList = targetDayUserArrangeHolder.getArrangeTypeList();

						ArrangeType targetArrangeType = null;
						if (targetArrangeTypeList.size() > 1) {
							targetArrangeType = targetArrangeTypeList.get(targetDayUserArrangeHolder.getCheck());
						} else {
							targetArrangeType = targetArrangeTypeList.iterator().next();
						}

						params.put("uid", tokenKeeper.getOpenId());
						params.put("to_uid", toUser.getUid());
						params.put("time", OtherUtils.maxLength(date.getTime()));
						params.put("circle_id", tokenKeeper.getUser().circleId());
						params.put("type", type);//1排班,2换班,3替班
						params.put("arrange_type_id", targetArrangeType.getId());

					} else if (arrangeIds.size() == 1) {

						params.put("uid", tokenKeeper.getOpenId());
						params.put("to_uid", toUser.getUid());
						params.put("time", OtherUtils.maxLength(date.getTime()));
						params.put("circle_id", tokenKeeper.getUser().circleId());
						params.put("type", type);//1排班,2换班,3替班

						DayUserArrangeHolder targetDayUserArrangeHolder = dayUserArrangeHolderList.get(0);
						List<ArrangeType> targetArrangeTypeList = targetDayUserArrangeHolder.getArrangeTypeList();

						ArrangeType targetArrangeType = null;
						if (targetArrangeTypeList.size() > 1) {
							targetArrangeType = targetArrangeTypeList.get(targetDayUserArrangeHolder.getCheck());
						} else {
							targetArrangeType = targetArrangeTypeList.iterator().next();
						}

						params.put("arrange_type_id", targetArrangeType.getId());

					}

				}

				ApiRequest.arrangeActionExchange.request(this, params);

			}

		} else {
			ViewUtils.toast("请选择排班");
		}

	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

		//某周的第一天
		Date date = data.get(position);

		//当前周天
		List<Date> weekDates = DateUtils.dateToWeek(date);

		//第几周
		int week = DateUtils.getWeekInYear(date);

		if (week == 1) {//当第一周时， 取本周最后一天的年月
			Date lastDateOfWeek = weekDates.get(weekDates.size() - 1);

			//哪年 - 取当前周最后一天日期的年数据
			int year = DateUtils.getYear(lastDateOfWeek);

			weekViewRequest(year, week);

		} else {//其它情况，当前周任意天即可

			Date dateOfWeek = weekDates.iterator().next();

			//哪年 - 取任意一天日期的年数据
			int year = DateUtils.getYear(dateOfWeek);

			weekViewRequest(year, week);

		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	public ViewGroup getViewWeekLayout() {
		return viewWeekLayout;
	}

	public DragSortListView getListView() {
		return listview;
	}

	public Spinner getSpinner() {
		return spinner;
	}

	public int getActionType() {
		return actionType;
	}

	public ViewGroup getClickView() {
		return clickView;
	}

	public void setClickView(ViewGroup clickView) {
		this.clickView = clickView;
	}

	public List<Integer> getArrangeIds() {
		return arrangeIds;
	}

	public ViewGroup getExchangeLayout() {
		return exchangeLayout;
	}

	public ViewGroup getArrangeLayout() {
		return arrangeLayout;
	}

	public ViewGroup getArrangeTypeLayout() {
		return arrangeTypeLayout;
	}

	public View getArrangeBtnReplace() {
		return arrangeBtnReplace;
	}

	public View getArrangeBtnExchange() {
		return arrangeBtnExchange;
	}

	public View getArrangeBtnExchangeAction() {
		return arrangeBtnExchangeAction;
	}

	public List<DayUserArrangeHolder> getDayUserArrangeHolderList() {
		return dayUserArrangeHolderList;
	}

	public void setDayUserArrangeHolderList(List<DayUserArrangeHolder> dayUserArrangeHolderList) {
		this.dayUserArrangeHolderList = dayUserArrangeHolderList;
	}

	public TextView getWeekRemark() {
		return weekRemark;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getType() {
		return type;
	}

	public String getDefSelectUid() {
		return defSelectUid;
	}

	public long getDefSelectTime() {
		return defSelectTime;
	}

	public void setArrangeTypeList(List<ArrangeType> arrangeTypeList) {
		this.arrangeTypeList = arrangeTypeList;
	}

	public ViewGroup getViewWeekHeaderLayout() {
		return viewWeekHeaderLayout;
	}

	public void setViewWeekHeaderLayout(ViewGroup viewWeekHeaderLayout) {
		this.viewWeekHeaderLayout = viewWeekHeaderLayout;
	}

	public List<ArrangeView> getArrangeViewList() {
		return arrangeViewList;
	}

	public int getCurWhich() {
		return curWhich;
	}

	public long getTime() {
		return time;
	}
	
}
